Page({
  data: {
    record: {},
    total: [],
    correctAnswer: '',
    select: '',
    currentIndex: 0, // 添加当前题目的索引
    Ai_content: '', // 存储 AI 返回内容
    modalName: null,
    loading: true // 添加 loading 状态
  },

  onLoad(options) {
    const id = options._id;
    console.log('传过来的id', id);
    this.getDtails(id);
  },

  getDtails: function (id) {
    const db = wx.cloud.database();
    db.collection('answer_record').doc(id).get().then(res => {
      if (res.data.answers && res.data.answers.length > 0) {
        console.log('数据', res.data.answers);
        this.setData({
          total: res.data.answers,
          record: res.data.answers[0], // 初始时设置为第一组内容
          correctAnswer: res.data.answers[0].correctAnswer,
          select: res.data.answers[0].selectedOption
        });
      } else {
        console.log('No answers found');
      }
    }).catch(err => {
      console.error('Failed to get details', err);
    });
  },

  nextQuestion: function () {
    if (this.data.currentIndex < this.data.total.length - 1) {
      const nextIndex = this.data.currentIndex + 1; // 增加当前索引
      const nextRecord = this.data.total[nextIndex]; // 获取下一题的记录

      // 更新数据
      this.setData({
        record: nextRecord,
        correctAnswer: nextRecord.correctAnswer,
        select: nextRecord.selectedOption,
        currentIndex: nextIndex // 更新当前索引
      });
    } else {
      wx.showToast({
        title: '已到最后一题',
        icon: 'none'
      });
    }
  },

  previousQuestion: function () {
    if (this.data.currentIndex > 0) {
      const previousIndex = this.data.currentIndex - 1; // 减少当前索引
      const previousRecord = this.data.total[previousIndex]; // 获取上一题的记录

      // 更新数据
      this.setData({
        record: previousRecord,
        correctAnswer: previousRecord.correctAnswer,
        select: previousRecord.selectedOption,
        currentIndex: previousIndex // 更新当前索引
      });
    } else {
      wx.showToast({
        title: '这是第一题',
        icon: 'none'
      });
    }
  },

  hideModal(e) {
    this.setData({
      modalName: null
    });
  },

  getAi: function (e) {
    // 打开模态框并清空上次的 Ai_content，同时设置 loading 为 true
    this.setData({
      modalName: 'DialogModal1',
      Ai_content: '', // 清空 AI 内容
      loading:true // 开始加载
    });

    const url_token = "https://aip.baidubce.com/oauth/2.0/token?client_id=twL58QrRtT291fVD8ySSL0Cy&client_secret=f0WiN9Z15Pjw383XfF8PjmGnUr7gjhVm&grant_type=client_credentials";
    const that = this;
    
    wx.request({
      url: url_token,
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      success: res => {
        console.log(res.data.access_token);
        const access_token = res.data.access_token;
        const url_chat = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + access_token;

        const payload = {
          "messages": [
            {
              "role": "user",
              "content": this.data.record.question
            }
          ]
        };

        wx.request({
          url: url_chat,
          method: "POST",
          data: payload,
          header: {
            'Content-Type': 'application/json'
          },
          success: function (res) {
            console.log('对话', res.data);
            // 请求成功后更新 Ai_content，并将 loading 设置为 false
            that.setData({
              Ai_content: res.data.result,
              loading:false // 请求完成，关闭加载状态
            });
          },
        });
      },
    });
  }
});
